package com.fujimana.android.manacode;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.fujimana.android.manacode.FileListDialog.FileListDialogListener;
import com.fujimana.android.manacode.loalder.LoaderFactory;
import com.fujimana.android.manacode.loalder.Sources;

public class ManacodeActivity extends Activity implements FileListDialogListener {
	
	private ActionBar actionBar;
	
	private Map<String, Sources> cache;
	
	private Map<String, TabRelation> relation;
	
	@Override  
	public Object onRetainNonConfigurationInstance() {
		return new Keep(this.cache, this.relation);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Keep keep = (Keep) getLastNonConfigurationInstance();
		
		this.relation = new HashMap<String, TabRelation>();
		this.cache = new HashMap<String, Sources>();
		
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		this.actionBar = getActionBar();

		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		if(keep != null) {
			
			Set<String> path = keep.getCache().keySet();
			for(String str : path) {
				createSourceTree(str);
				
				TabRelation relation = keep.getRelation().get(str);
				if(relation == null) {
					continue;
				}
				
				for(String str2 : relation.getChild()) {
					try {
						createSourceView(str, str2);
					} catch (IOException e) {
						throw new ManacodeException(e);
					}
				}
			}
			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.tree_menu, menu);
		return true;
	}
	
	void createSourceView(String id, String path) throws IOException {
		if(path.startsWith("/")) {
			path = path.substring(1);
		}
		
		if(relation.containsKey(path)) {
			
			int count = actionBar.getTabCount();
			for(int i=0; i<count; i++) {
				Tab t = actionBar.getTabAt(i);
				
				if(path.equals(t.getTag())) {
					t.select();
					return;
				}
			}
		}
		
		Sources archive = this.cache.get(id);
		
		String source = archive.getSource(path);
		
		LinearLayout layout = (LinearLayout)findViewById(R.id.parent);
		
		Tab tab = actionBar.newTab();
		tab.setIcon(R.drawable.source);
			
		SourceViewListener listener = new SourceViewListener(layout, this,source, path, "java");
		tab.setTabListener(listener);
		
		TabRelation relation = new TabRelation();
		relation.setId(path);
		this.relation.put(path, relation);
		
		this.relation.get(path).getChild().add(path);
		
		actionBar.addTab(tab);
		actionBar.selectTab(tab);
	}
	
	void createSourceTree(String path) {
		
		int count = actionBar.getTabCount();
		for(int i=0; i<count; i++) {
			Tab t = actionBar.getTabAt(i);
			
			if(t.getTag().equals(path)) {
				t.select();
				return;
			}
		}
		
		Sources archive = read(path);
	
		LinearLayout layout = (LinearLayout)findViewById(R.id.parent);
		
		Tab tab = actionBar.newTab();
		tab.setIcon(R.drawable.tree);
			
		SourceTreeListener listener = new SourceTreeListener(layout, this, archive, path);
		tab.setTabListener(listener);
		
		TabRelation relation = new TabRelation();
		relation.setId(path);
		this.relation.put(path, relation);
		
		actionBar.addTab(tab);	
		actionBar.selectTab(tab);
		
		tab.setTag(path);
		this.cache.put(path, archive);
	}
	
	private Sources read(String path) {	
		try {
			String encoding = getEncoding();
			Sources archive = LoaderFactory.getInstance().getSources(path, encoding);
			archive.read();
			return archive;
		} catch (IOException e) {
			return null;
		}
	}
	
	private String getEncoding() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		String def = System.getProperty("file.encoding");
		if (def == null || def.trim().equals("")) {
			def = "UTF-8";
		}
		
		String encoding= prefs.getString(this.getString(R.string.settings_encoding_key), def);
		return encoding;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int id = item.getItemId();

		if (id == R.id.settings) {
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
		} else if (id == R.id.exit) {
			this.moveTaskToBack(true);
			this.finish();
		} else if (id == R.id.open) {
			FileListDialog dlg = new FileListDialog(this);
			dlg.setOnFileListDialogListener(this);
			File file = Environment.getExternalStorageDirectory();
			dlg.show(file.getPath(), file.getPath());
		} else if(id == R.id.close) {
			Tab tab = actionBar.getSelectedTab();
			deleteTab(tab);
		}

		return true;
	}
	
	private void deleteTab(Tab tab) {
		actionBar.removeTab(tab);
		this.cache.remove(tab.getTag());
		
		TabRelation relation = this.relation.get(tab.getTag());
		
		int count = actionBar.getTabCount();
		for(int i=0; i<count; i++) {
			Tab t = actionBar.getTabAt(i);
			
			if(relation.getChild().contains(t.getTag())) {
				deleteTab(t);
			}
		}
		
		this.relation.remove(tab.getTag());
	}

	@Override
	public void onClickFileList(File file) {
		createSourceTree(file.getPath());
	}
	
}